package com.medical.logback.filter;

import com.medical.logback.interceptor.RequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.UUID;

/**
 * @Auther:gzf
 * @Date : 2022/06/23
 */
@Slf4j
@Component
public class LogFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        long start = System.currentTimeMillis();
        ServletRequest requestWrapper = null;
        if (servletRequest instanceof HttpServletRequest) {
            requestWrapper = new RequestWrapper((HttpServletRequest) servletRequest);
        }
        if (requestWrapper == null) {
            printParam(servletRequest);
            filterChain.doFilter(servletRequest, servletResponse);
            printTotalTime(servletRequest, start);
        } else {
            printParam(requestWrapper);
            filterChain.doFilter(requestWrapper, servletResponse);
            printTotalTime(requestWrapper, start);
        }
    }

    /*
     * @Author: gzf
     * @Date: 2022/6/24
     * @Description:
     */
    private void printParam(ServletRequest servletRequest) throws UnsupportedEncodingException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        MDC.put("traceId", UUID.randomUUID().toString().replaceAll("-", ""));
        String method = request.getMethod();
        if ("POST".equals(method)) {
            RequestWrapper requestBodyWrapper = new RequestWrapper(request);
            String body = requestBodyWrapper.getBody();
            log.info(" requestUri:{}, requestParam:{}", request.getRequestURL().toString(), body);
        }
        if ("GET".equals(method)) {
            String queryString = request.getQueryString();
            if (!StringUtils.isEmpty(queryString)) {
                String requestParam = URLDecoder.decode(queryString, "utf-8");
                log.info(" requestUri:{}, requestParam:{}", request.getRequestURL().toString(), requestParam);
            }
        }
    }

    private void printTotalTime(ServletRequest servletRequest, long startTime) {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        long endTime = System.currentTimeMillis();
        log.info(" 请求url:{} , 耗时: {}ms", request.getRequestURL().toString(), (endTime - startTime));
        MDC.clear();
    }

}
